Next | Prev | Up | Top | Contents | Index
General-Purpose Allocation
There are two groups of general-purpose functions used to allocate and release memory.
- kmem_alloc() and two associated functions supply a complete set of services for allocating kernel virtual memory.
- kern_malloc() and two associated functions are an obsolete mechanism for allocating kernel virtual memory.
The functions you can use to dynamically allocate kernel virtual memory are summarized in Table 9-3.
Functions for Kernel Virtual Memory
Function Name | Header Files | Can Sleep? | Purpose |
---|
kmem_alloc(D3) | kmem.h & types.h | Y | Allocate space from kernel free memory. |
kmem_free(D3) | kmem.h & types.h | N | Free previously allocated kernel memory. |
kmem_zalloc(D3) | kmem.h & types.h | Y | Allocate and clear space from kernel free memory. |
kern_calloc(D3) | systm.h & types.h | Y | Allocate space from kernel memory and clear it. |
kern_free(D3) | systm.h & types.h | N | Free kernel memory space. |
kern_malloc(D3) | systm.h & types.h | Y | Allocate kernel virtual memory. |
The most important of these functions is kmem_alloc(). You use it to allocate blocks of virtual memory at any time. It offers these important options, controlled by a flag argument:
- Sleeping or not sleeping when space is not available. You specify not-sleeping when in a lower-half routine or when holding a basic lock, but then you must be prepared to deal with a return value of NULL.
- Physically-contiguous memory. The memory allocated is virtual, and when it spans multiple pages, the pages are not necessarily adjacent in physical memory. You need physically contiguous pages when doing DMA with a device that cannot do scatter/gather. However, contiguous memory is harder to get as the system runs, so it is best to obtain it in an initialization routine.
- Cache-aligned memory. By requesting memory that is a multiple of a cache line in size, and aligned on a cache-line boundary, you ensure that DMA operations will affect the fewest cache lines (see "Setting Up a DMA Transfer").
The kmem_zalloc() function takes the same options, but offers the additional service of zero-filling the allocated memory.
Calls to the "kern" group of functions should be replaced as follows:
kern_malloc(n) | Change to kmem_alloc(n,KM_SLEEP). |
kern_calloc(n,s) | Change to kmem_zalloc(n*s,KM_SLEEP) |
kern_free(p) | Change to kmem_free(p) |
Next | Prev | Up | Top | Contents | Index